import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 1. 读取数据
df = pd.read_excel(
    "Monthly_Counts_Quad&Event.xlsx",
    sheet_name="QuadClass",
    parse_dates=["Month"]
)
df = df.sort_values("Month")

# 2. 全局字体设置为 Times New Roman
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif']  = ['Times New Roman']

# 3. 公共参数
start_base = pd.Timestamp("2014-01-01")
end_base   = df["Month"].max()
bar_width  = pd.Timedelta(days=20)  # 用于左右缓冲

# 4. 原列名（整数）与配色
colors = {
    1: "#66c2a5",  # Verbal Cooperation
    2: "#fc8d62",  # Material Cooperation
    3: "#8da0cb",  # Verbal Conflict
    4: "#e78ac3"   # Material Conflict
}

# 5. 绘制堆叠柱状图
fig, ax = plt.subplots(figsize=(14, 6))
bottom = pd.Series(0, index=df.index)

for col, color in colors.items():
    ax.bar(
        df["Month"], df[col].astype(float),
        width=bar_width, bottom=bottom,
        color=color
    )
    bottom += df[col].astype(float)

# 6. 首尾缓冲
ax.set_xlim(
    start_base - bar_width/1,
    end_base   + bar_width/1
)

# 7. 刻度与网格
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=range(1,13,4)))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.xaxis.set_minor_locator(mdates.MonthLocator())
plt.setp(ax.get_xticklabels(), rotation=45, ha='right')
ax.grid(which='major', axis='both', linestyle='--', linewidth=0.5)

# 8. 自定义图例映射
legend_labels = [
    "1: Verbal Cooperation",
    "2: Material Cooperation",
    "3: Verbal Conflict",
    "4: Material Conflict"
]
ax.legend(legend_labels, loc='upper left', frameon=False,
          prop={'family':'Times New Roman'})

# —— 由你自行添加标题和轴标签 ——
# 例如：
# ax.set_xlabel("Month", fontfamily='Times New Roman')
# ax.set_ylabel("Count", fontfamily='Times New Roman')
# ax.set_title("QuadClass 2014-01 起堆叠柱状图", fontfamily='Times New Roman')

plt.tight_layout()
fig.savefig('Quadclass_300dpi.jpg', dpi=300)
plt.show()
